<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\home\controller;


use app\wechat\service\FansService;
use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use service\WechatService;
use think\App;
use think\Db;
use think\facade\Cache;
use think\Session;
use service\HttpService;



/**
 * 微信登录
 * @author caicai
 */

class Login extends BasicAdmin
{
    private $appkey = '27865a233720b7fc'; //API
    private $appurl = 'http://api.jisuapi.com/todayhistory/query';
    /**
     * 微信登录
     * unionid保证同一个用户使用两个产品，如果是推送消息 那么必须用openid来保证 不同的应用不同的推送
     *
     *
     * @return \think\App
     */
    public function index()
    {
        $code = $this->request->post('code');
        $iv = $this->request->post('iv');
        $encryptedData = $this->request->post('encryptedData');

        //获取信息
        $userInfo = WechatService::WeMiniCrypt()->userInfo($code, $iv, $encryptedData);
        $userInfo['nickname'] = $userInfo['nickName'];
        $userInfo['sex'] = $userInfo['gender'];
        $userInfo['headimgurl'] = $userInfo['avatarUrl'];
        $userInfo['unionid'] = $userInfo['unionId'];
        $userInfo['appid'] = sysconf('mini_appid');


        $WechatFans = Db::name('WechatFans');
        //判断是否是新用户，数据库入库操作
        $fans = $WechatFans->where(['openid' => $userInfo['openId'] , 'appid' => $userInfo['appid'] ])->find();
        if (!$fans){
            FansService::set($userInfo);
        }
        $userInfo['id'] = $fans['id'];
        $userInfo['phone'] = $fans['phone'];
        $userInfo['birthday'] = $fans['birthday'];
        $userInfo['constellation'] = $fans['constellation'];
        unset($userInfo['nickName'],$userInfo['gender'],$userInfo['avatarUrl'],$userInfo['unionId']);

        $userInfo['session3rd'] = substr(md5($userInfo['openId']), 8, 16);//生成第三方sessionid
        Cache::set('userInfo' , $userInfo , 60*60*12);


        return json_encode($userInfo);
    }



    /**
     * 历史上的今天列表
     */

    public function today(){
        return $this->setToday();
    }

    /**
     * 历史的今天api请求
     * @return string
     */
    private function setToday(){

        $m = (int) $this->request->post('month' , date('m'));
        $d = (int) $this->request->post('day' , date('d'));
        $url = $this->appurl;
        $get = [
            'appkey' => $this->appkey,
            'month' => $m,
            'day' =>  $d,
            ];
        for ($i=0 ; $i<3 ; $i++){
            //接口暂时挂了
//            $data = HttpService::get($this->appurl , $get,['timeout'=>10] );
//            $data = json_decode($data,true);
            $data = [];

            if (!empty($data) && $data['status'] == 0){
                $res = json_encode(current($data['result']));
                return $res;
            } else {
                $url = "https://www.ipip5.com/today/api.php?type=json";
                $data1 = file_get_contents("compress.zlib://".$url);
                $data1 = json_decode($data1,true);
                $res = current($data1['result']);
                $res['month'] = $m;
                $res['day'] = $d;
                $res['pic'] = isset($this->getBanner(1)['value']) ? $this->getBanner(1)['value'] :'../images/banner04.png' ;
                return json_encode($res);
            }
        }
    }


    /**
     * 明星生日展示
     * 支持生日查询，月份查询，姓名查询
     */
    public function getTodayStar(){

        $db = Db::name('WechatStar');
        $post = $this->request->post();
        if (empty($post)){
            $post['birthday'] = '_'.date('m-d');
            $res = $db->whereLike('birthday', "%{$post['birthday']}%")->select();
        } else {
            isset($post['birthday']) && $post['birthday'] = date('m-d',strtotime($post['birthday']));
            foreach (['name','birthday'] as $key) {
                isset($post[$key]) && $db->whereLike($key, "%{$post[$key]}%");
            }
            $res = $db->select();
        }

        //计算节日
        $holiday = $this->getHoliday();
        return json_encode(['star'=>$res,'holiday'=>$holiday]);

    }

    /**
     * 获取本月好友生日列表
     * wechat_fans_relation
     */

    public function getFriendBirthday() {

        $userInfo = Cache::get('userInfo');
        $userInfo['id'] =2;
        $month = '-'.date('m').'-';
        $month_next = '-'.date('m',strtotime('+1 month')) .'-';

        $friends = Db::name('wechatFansRelation')->where(['user_id'=>$userInfo['id'],'is_follow'=>1])->select();
        $friends_arr = array_column($friends,'friend_id');
        $data = Db::name('wechatFans')->whereIn('id', $friends_arr)->whereLike('birthday', "%{$month}%")->limit(2)->select();

        $data_next = Db::name('wechatFans')->whereIn('id', $friends_arr)->whereLike('birthday', "%{$month_next}%")->limit(2)->select();

        foreach ($data as &$item) {
            $item['desc'] = ToolsService::getTimeDesc(date('Y-').date('m-d',strtotime($item['birthday'])));
            $item['birthday'] = date('m月d日',strtotime($item['birthday']));
        }
        foreach ($data_next as &$item) {
            $item['desc'] = ToolsService::getTimeDesc(date('Y-').date('m-d',strtotime($item['birthday'])));
            $item['birthday'] = date('m月d日',strtotime($item['birthday']));
        }

        return json_encode(['data'=>$data,'data_next'=>$data_next]);
    }

    /**
     * 获取最近的2节日
     * wechat_fans_relation
     */

    public function getHoliday() {
        //0默认当月，1默认下个月
        $date = date('Y-m-d');
        $data = Db::name('holiday')->whereTime('date', '>=', $date)->limit(2)->select();
        foreach ($data as &$item) {
            $item['desc'] = ToolsService::getTimeDesc($item['date']);
            $item['date'] = date('m月d日',strtotime($item['date']));
            $item['pic'] = $item['pic']!="" ? $item['pic'] : '../images/banner02.png';
        }

        return $data;
    }

    /**
     * 获取星座运势
     * @return string
     */
    public function getConstellationFate() {
        $userInfo = Cache::get('userInfo');
        $constellation = empty($userInfo['constellation']) ? ToolsService::get_constellation(date('Y-m-d')) : $userInfo['constellation'];
        $data = ToolsService::get_constellation_fate($constellation);
        $data['pic'] = isset($this->getBanner(2)['value']) ? $this->getBanner(2)['value'] :'../images/banner01.png' ;


        //随机分数
        $progress_txt = Cache::get('CACHE_FATE_'.$constellation);
        $diff = strtotime(date("Y-m-d",strtotime("+1 day")))-time();//还有10分钟的时候强制刷新
        if ($progress_txt && $diff>60*10) {
            $data['progress_txt'] = $progress_txt;
        }else {
            $progress_txt = rand(50,100);
            $data['progress_txt'] = $progress_txt;
            Cache::set('CACHE_FATE_'.$constellation,$progress_txt,24*60*60);
        }
        return json_encode($data);
    }

    /**
     * 获取指定banner
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Collection|\think\Model
     */
    private function getBanner($id){

        $db = Db::name('WechatBanner');
        if (is_array($id)) {
            $data = $db->whereIn('id',$id)->select();
        }else {
            $data = $db->where(['id'=>$id])->find();
        }
        return $data;
    }
}
